package org.jflame.context.mybatis;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

/**
 * json列类型处理器.
 * <p>
 * 注:不适合java集合类型
 * 
 * @author charles.zhang
 */
public abstract class AbstractJsonTypeHandler<T> extends BaseTypeHandler<T> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setString(i, toJson(parameter));
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String textValue = rs.getString(columnName);
        return StringUtils.isBlank(textValue) && rs.wasNull() ? null : fromJson(textValue);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String textValue = rs.getString(columnIndex);
        return StringUtils.isBlank(textValue) && rs.wasNull() ? null : fromJson(textValue);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String textValue = cs.getString(columnIndex);
        return StringUtils.isBlank(textValue) && cs.wasNull() ? null : fromJson(textValue);
    }

    protected abstract String toJson(Object parameter);

    protected abstract T fromJson(String textValue);

}
